# -*- coding:utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
import re

def trunc_text(text, limit_chars, ending='...', by_spaces=False):
    """
    Truncate given text by symbols or words and add "..." or antother ending.
    """
    limit_chars -= len(ending)
    if len(text) > limit_chars:
        truncated = text[0:limit_chars]
        if not truncated:
            return text
        if by_spaces:
            truncated = truncated.rsplit(' ', 1)[0]
        return truncated + ending
    return text

def load_class(path):
    """
    Return class object from full module.package.class path
    """
    try:
        dot = path.rindex('.')
    except ValueError:
        raise Exception, 'Invalid class path: %s' % path
    module, classname = path[:dot], path[dot + 1:]
    try:
        mod = __import__(module, {}, {}, [''])
    except ImportError, e:
        raise Exception, 'Error importing class %s: "%s"' % (module, e)
    try:
        return getattr(mod, classname)
    except AttributeError:
        raise Exception, 'Middleware module "%s" does not define a "%s" class' % (module, classname)

def assert_has_request(context):
    if not 'request' in context:
        raise ImproperlyConfigured('Add "django.core.context_processors.request" request processor to TEMPLATE_CONTEXT_PROCESSORS section of settings.py')

SLUGIFY_TABLE = {
    u'а': 'a',
    u'б': 'b',
    u'в': 'v',
    u'г': 'g',
    u'д': 'd',
    u'е': 'e',
    u'ё': 'io',
    u'ж': 'j',
    u'з': 'z',
    u'и': 'i',
    u'й': 'yi',
    u'к': 'k',
    u'л': 'l',
    u'м': 'm',
    u'н': 'n',
    u'о': 'o',
    u'п': 'p',
    u'р': 'r',
    u'с': 's',
    u'т': 't',
    u'у': 'u',
    u'ф': 'f',
    u'х': 'h',
    u'ц': 'ts',
    u'ч': 'ch',
    u'ш': 'sh',
    u'щ': 'shch',
    u'ы': 'y',
    u'э': 'ye',
    u'ю': 'yu',
    u'я': 'ya',
    u'ă': 'a',
    u'î': 'i',
    u'ţ': 't',
    u'â': 'a',
    u'ş': 's',
    u' ': '-',
    u'_': '-',
    u'+': '-',
    u'-': '-',
}
SLUGIFY_TABLE.update(dict((x, x) for x in 'qwertyuiopasdfghjklzxcvbnm1234567890'))

_double_minus_re = re.compile('(-{2,})', re.UNICODE)
def slugify(s, max_length=50):
    result = ''.join(SLUGIFY_TABLE.get(sym, '') for sym in s.lower())
    return  _double_minus_re.sub('-', result)[:max_length]

